<?php

namespace app\home\controller;

use think\Controller;
use think\Db;
use think\Session;
use codes\Qrcode;

class Login extends Controller
{
    // 登录操作
    public function doLogin()
    {
         //需要手机号phone，密码password
        session(null);//清空user信息
        $phone = input('phone');
        $password = input('password');
        if(!$phone || !$password){
            return json(['status'=>-1,'message'=>'登錄信息不完善！']);
        }
        $user = db('users')->where(['phone'=>$phone])->find();
        if($user['status'] == 2){
            return json(['status'=>-1,'message'=>'您已被系統拉黑，請聯系客服！']);
        }
        if(!$user || (md5($password) != $user['password'])){
            return json(['status'=>-1,'message'=>'賬號或密碼錯誤']);
        }
        $user = db('users')->where(['phone'=>$phone])->find();
        // session('home.user',$user);
        session('uid',$user['id']);
        return json(['status'=>200,'message'=>'登錄成功','data'=>$user['id']]);

    }
    #用户注册
    public function register()
    {
        $param = input('param.');
        if (null === $param['phone']) {
            return json(['status'=>-1,'message'=>'手機號不能為空']);
        }
        $user = Db::name('users')->where('phone',$param['phone'])->value('id');
        if ($user) {
            return json(['status'=>-1,'message'=>'手機號已被註冊']);
        }
        
        if (null === $param['unique'] || empty($param['unique'])) {
            return json(['status'=>-1,'message'=>'無推薦碼,不可註冊']);
        }
        $pid = db('users')->where('unique',$param['unique'])->value('id');
        if(!$pid){
            return json(['status'=>-1,'message'=>'無推薦碼,不可註冊']);
        }
        $prg = "/\w{6,18}$/";
        if (!preg_match($prg, $param['password'])) {
            return json(['status' => -1, 'message' => '密碼長度在6~18之間，只能包含字符、數字或下劃線']);
        }

        if ($param['password'] != $param['two_password']) {
            return json(['status' => -1, 'message' => '兩次輸入密碼不壹致']);
        }

        $prg = "/\d{6}$/";
        if (!preg_match($prg, $param['pay_password'])) {
            return json(['status' => -1, 'message' => '支付密碼為6位純數字']);
        }

        if ($param['code'] != db('sms')->where(['phone'=>$param['phone'],'status'=>0,'type'=>1])->value('code') ) {
            return json(['status'=>-1,'message'=>'驗證碼錯誤']);
        }
        Db::startTrans();
        try {
            db('sms')->where(['phone'=>$param['phone'],'status'=>0,'type'=>1])->update(['status'=>1]);
            $unique = getuserid();
            $new = [
                'phone'         => $param['phone'],
                'unique'        => $unique,
                'stack'         => md5($unique),
                'password'      => md5($param['password']),
                'two_password'  => md5($param['pay_password']),
                'nickname'      => 'y-'.$param['phone'],
                'pid'           => $pid,
                'create_time'    => date('YmdHis')
            ];
            
            $id = db('users')->insertGetId($new); //用户
            $pidInfo = db('user_position')->where('uid',$pid)->field('pid,lay')->select();
            #添加节点关系
            $action = [];
            if ( empty($pidInfo) ) {
                $action['uid'] = $id;
                $action['pid'] = $pid;
                $action['lay'] = 1;
                $action['create_time'] = date('YmdHis');
                $action['is_effective'] = 1;
                db('user_position')->insert($action);
            }else{
                $action[0]['uid'] = $id;
                $action[0]['pid'] = $pid;
                $action[0]['lay'] = 1;
                $action[0]['create_time'] = date('YmdHis');
                $action[0]['is_effective'] = 1;
                foreach ($pidInfo as $k => $v) {
                    $action[$k + 1]['uid'] = $id; 
                    $action[$k + 1]['pid'] = $v['pid']; 
                    $action[$k + 1]['lay'] = $v['lay'] + 1; 
                    $action[$k + 1]['create_time'] = date('YmdHis');
                    $action[$k + 1]['is_effective'] = 1;
                }
                db('user_position')->insertAll($action);
            }
            Db::commit();
        } catch (Exception $e) {
            return json(['status'=>-1,'message'=>'註冊失敗']);
        }
        session(null);
        return json(['status' => 200, 'message' => '註冊成功']);
    }

    #发送验证码
    public function code()
    {
        if(empty(input('phone'))){
            return json(['status'=>-1,'message'=>'手机号不能为空']);
        }
//        type = 1:注册，type=2：忘记
        $type = (int)input('type')?:1;
        $phone = input('phone');
        if(in_array($phone, config('phones'))){
            return json(['status'=>200,'message'=>'發送成功']);
        }
        $res = db('users')->where(['phone'=>$phone])->find();
        switch ($type) {
            case 1:
                if($res)return json(['status'=>-1,'message'=>'手機號已被註冊']);
                break;
            case 2:
                if(!$res)return json(['status'=>-1,'message'=>'該手機號未註冊']);
                break;
            case 3:
                if(!$res)return json(['status'=>-1,'message'=>'該手機號未註冊']);
                break;
            case 4:
                if(!$res)return json(['status'=>-1,'message'=>'該手機號未註冊']);
                break;
            case 5:
                if(!$res)return json(['status'=>-1,'message'=>'該手機號未註冊']);
                break;
            case 7:
                if(!$res)return json(['status'=>-1,'message'=>'該手機號未註冊']);
                break;
            case 6:
                $res1 = db('users')->where(['phone'=>input('two_phone')])->find();
                if(!$res)return json(['status'=>-1,'message'=>'該手機號未註冊']);
                if($res1)return json(['status'=>-1,'message'=>'手機號已被註冊']);
                break;
        }

        $result = NewSms($phone,$type);
        if($result['data'] > 0){
            return json(['status'=>200,'message'=>'發送成功']);
        }else{
            return json(['status'=>-1,'message'=>'發送失敗']);
        }
    }
    #忘记登录密码
    public function getPwd()
    {
        #需要验证码code ,密码password,再次密码two_password
        $phone = input('phone');
        $user  = db('users')->where(['phone' => $phone])->find();
        if (!$user) {
            return json(['status' => -1, 'message' => '賬號不存在']);
        }
        $code         = input('code');
        $password     = input('password');
        $two_password = input('qr_password');
        if ($password != $two_password) {
            return json(['status' => -1, 'message' => '密碼不匹配']);
        }
        if(!in_array($phone, config('phones'))){
            if (!$code) {
                return json(['status' => -1, 'message' => '驗證碼不能為空']);
            }
            if (input('param.code') != db('sms')->where(['phone' => $phone, 'status' => 0, 'type' => 2])->value('code')) {
                return json(['status' => -1, 'message' => '驗證碼錯誤']);
            }
            db('sms')->where(['phone' => $phone, 'status' => 0])->update(['status' => 1]);

        }
        
        $update['password'] = md5($password);
        db('users')->where(['phone' => $phone])->update($update);
        return json(['status' => 200, 'message' => '找回密碼成功']);
    }

    #推广二维码
    public function promotion()
    {
        $id = input('unique');
        if($id){
            $user = db('users')->where(['unique'=>$id])->find();
        }else{
           $id = session('uid'); 
            $user = db('users')->where(['id'=>$id])->find();
        }
        if(!$id ){
            return json(['status'=>-1,'message'=>'您還沒有登錄']);
        }
        $return = [];
        $return['todayPrice'] = db('config')->where('id',1)->field('dollar,RMB')->find();
        $return['Carousel'] = db('carousel')->select();
        $return['phone'] = $user['phone'];
        // if(!is_file('./userimg/qrcode/'.$user['unique'].'.png')){
            $path = ROOT_PATH.'public/userimg/qrcode/'.$user['unique'].'.png';
            Qrcode::png(FRDOMAIN.'/register?pid='.$user['unique'],$path);
        // }
        $return['qrcode'] = DOMAIN.'/userimg/qrcode/'.$user['unique'].'.png';
        $article = db('article')->column('id');

        if (!empty($article) && !empty($user['read_notice'])) {
             $arr = explode(",", trim($user['read_notice'],",")); 
             if (count($article) != count($arr)) {
                 $return['articleNum']= 1;
             }else{
                $return['articleNum'] = 0;
             }
        }else if (empty($user['read_notice'])) {
            $return['articleNum']= 1;
        }



        return json(['status'=>200,'message'=>'獲取成功','data'=>$return]);

    }
    #退出登录
    public function logout()
    {
        session(null);
        return json(['status'=>200,'message'=>'成功','data'=>'']);
    }   
        

    

}
